<?php
class Controller_Admin_pagedownload extends  Controller_Template {
	public function __construct($req, $res) {
		$this->template = "smarty:admin/page/feature";
		parent::__construct($req, $res);
	}

	public function action_feature()
	{
        $get = $this->request->query();
        $day = Arr::get($get,'day',date("Y-m-d",strtotime("-1 day")));
		$data = pageDownload::page_download("Featured",str_replace('/','-',$day));
		$this->template->set('downloads',$data);
		$this->template->set('day',$day);
		$this->template->set('sumdata',$this->sum_data($data));
	}

    public function action_position()
    {
        $get = $this->request->query();
        $start_day = Arr::get($get,'start_day',date("Y-m-d",strtotime("-30 day")));
        $end_day = Arr::get($get,'end_day',date("Y-m-d",strtotime("-1 day")));
        $index = Arr::get($get,'index',1);
        $this->template->set_filename('smarty:admin/page/position');
        $data = pageDownload::page_index("Featured",$index-1,$start_day,$end_day);
        $this->template->set('index',$index); 
        $this->template->set('start_day',str_replace('-','/',$start_day)); 
        $this->template->set('end_day',str_replace('-','/',$end_day)); 
		$this->template->set('downloads',$data);
		$this->template->set('sumdata',$this->sum_data($data));
        $this->set_charts($data);
    }

    private function set_charts($data)
    {
        $date_list = array(); 
        $counts = array();
        foreach($data as $val)
        {
            $date_key = Arr::get($val,'date',date('Y-m-d'));
            $date_list[] = $date_key;
            $counts[$date_key] = Arr::get($val,'list_download',0) + Arr::get($val,'detail_download',0);
        }
        $this->template->set('date_list',json_encode($date_list));
        $this->template->set('counts',json_encode(array_values($counts)));
    }
    

	private function sum_data($data)
	{
		$sum_data = 0;
		$counts = 0;
		foreach($data as $val)
		{
			$list_sum_data = $list_sum_data + $val['list_download'];
			$detail_sum_data = $detail_sum_data + $val['detail_download'];
			$counts = $counts + 1;
		}
		$rs = array(
			'detail_sum' => $detail_sum_data,
			'list_sum' => $list_sum_data,
			'counts' => $counts,
		);
		return $rs;
	}
}
